package com.mchat.communication.process.message.impl;

import com.mchat.common.dto.bo.OnlineUser;
import com.mchat.common.entity.user.User;
import com.mchat.common.utils.SystemUtil;
import com.mchat.communication.process.message.MessageProcessor;
import com.mchat.communication.process.message.MessageType;
import com.mchat.communication.protocol.IMMessage;
import com.mchat.communication.service.OnlineUserService;
import com.mchat.communication.service.UserService;
import io.netty.channel.Channel;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class LoginMsgProcessor implements MessageProcessor {
    @Resource
    private OnlineUserService onlineUserService;
    @Resource
    private UserService userService;

    @Override
    public void process(Channel client, IMMessage message) {
        OnlineUser onlineUser = getOnlineUser(client, message);
        IMMessage msg = IMMessage.builder().action(MessageType.LOGIN.getType())
                .time(SystemUtil.getSystemTime())
                .receiver("ALL")
                .content(message.getSender() + "加入聊天室")
                .online(onlineUserService.countOnlineUsers())
                .build();
        onlineUserService.addOnlineUser(onlineUser);
        onlineUserService.sendMessage(onlineUser, msg);
    }

    private OnlineUser getOnlineUser(Channel client, IMMessage message) {
        String userSeq = userService.getUserSeqByUserName(message.getSender());
        User user = userService.getUserBySeq(userSeq);
        OnlineUser onlineUser = new OnlineUser();
        onlineUser.setAvatar(user.getAvatar());
        onlineUser.setUserName(user.getUserName());
        onlineUser.setUserId(user.getId());
        onlineUser.setIpAddress(message.getAddress());
        onlineUser.setUserSeq(userSeq);
        onlineUser.setClient(client);
        return onlineUser;
    }

}
